package middleware

import (
	"context"
	"net/http"
	"trade_api/global"
	"trade_api/models/request"
	"trade_api/models/response"

	pb "trade_api/proto"

	"github.com/gin-gonic/gin"
)

func IsAdminAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		claims, _ := c.Get("claims")
		currentUser := claims.(*request.CustomClaims)
		if currentUser.AuthorityId != 1 {
			c.JSON(http.StatusForbidden, response.Response{
				Code:    http.StatusForbidden,
				Message: "当前用户没有权限",
			})
			c.Abort()
			return
		}
		c.Next()
	}
}

// IsPortalPorver 是否是PortalPorver
func IsPortalPorver() gin.HandlerFunc {
	return func(c *gin.Context) {
		claims, _ := c.Get("claims")
		currentUser := claims.(*request.CustomClaims)
		if currentUser.AuthorityId != 2 {
			c.JSON(http.StatusForbidden, response.Response{
				Code:    http.StatusForbidden,
				Message: "当前用户没有权限",
			})
			c.Abort()
			return
		}
		c.Next()
	}
}

// IsPortalRegisterd 门架是否已经注册
func IsPortalRegisterd() gin.HandlerFunc {
	return func(c *gin.Context) {
		// mac 地址
		macAddress := c.Request.Header.Get("mac")
		portalCode := c.Request.Header.Get("code")
		// TODO: 看看这个是不是放在redis比较好，不要再通过微服务调用来查询了
		_, err := global.PortalRpcClient.GetDevice(context.Background(), &pb.GetPortalDeviceRequest{
			MacAddress: macAddress,
			PortalCode: portalCode,
		})
		if err != nil {
			c.JSON(http.StatusForbidden, response.Response{
				Code:    http.StatusForbidden,
				Message: "当前设备没有注册",
			})
			c.Abort()
			return
		}
	}
}
